# coding:utf-8
# 大厅
# 负责 创建房间 进入的逻辑

import gnet
import account_mgr, player_mgr, room_mgr
from player import Player
import prt_hall




# 初始化
def init():
	print "hall>init"
	room_mgr.init()
	reg()


def reg():
	gnet.reg(prt_hall.ROOM_LIST, on_room_list)
	gnet.reg(prt_hall.CREATE_ROOM, on_create_room)
	gnet.reg(prt_hall.EXIT_ROOM, on_exit_room)
	gnet.reg(prt_hall.JOIN_ROOM, on_join_room)


# 房间列表
def on_room_list (data):
	print "on_room_list", data
	
	conn_id = data[0]

	room_id = 123
	room_name = "兔子的房间"
	room_mode = 1
	room_cur_player = 3
	room_max_player = 6
	room_is_password = 0
	aroom = [room_id, room_name, room_mode, room_cur_player, room_max_player, room_is_password]
	data = [aroom, aroom, aroom]
	gnet.send( conn_id, [ prt_hall.ROOM_LIST, data ] )


# 创建房间
def on_create_room (data):
	print "on_create_room", data
	
	conn_id = data[0]
	room_name = data[1]
	room_mode = data[2]

	p = player_mgr.get_player_by_conn_id(conn_id)
	if p == None:
		gnet.send( conn_id, [ prt_hall.CREATE_ROOM, 0 ] )
		return
	
	# 检测是否在房间中
	if p.get_cur_room() > 0:
		gnet.send( conn_id, [ prt_hall.CREATE_ROOM, 0 ] )
		return

	room_id = room_mgr.create_room(room_name, room_mode)
	if room_id > 0:

		p.set_cur_room(room_id)
		
		# msgid, room_id
		gnet.send( conn_id, [ prt_hall.CREATE_ROOM, room_id ] )
	else:
		gnet.send( conn_id, [ prt_hall.CREATE_ROOM, 0 ] )


# 加入房间
def on_join_room (data):
	print "on_join_room", data
	
	conn_id = data[0]
	room_id = data[1]

	p = player_mgr.get_player_by_conn_id(conn_id)
	if p == None:
		gnet.send( conn_id, [ prt_hall.JOIN_ROOM, 0 ] )
		return
	
	isOk = room_mgr.join_room(p, room_id)
	if isOk:
		# msgid, isOk
		gnet.send( conn_id, [ prt_hall.JOIN_ROOM, 1 ] )
	else:
		gnet.send( conn_id, [ prt_hall.JOIN_ROOM, 0 ] )


# 离开房间
def on_exit_room (data):
	print "on_exit_room", data
	
	conn_id = data[0]

	gnet.send( conn_id, [ prt_hall.EXIT_ROOM, 1 ] )




